<template>
  <!-- 导航栏 -->
  <van-nav-bar title="购物车" left-arrow @click-left="back"> </van-nav-bar>
  <van-checkbox-group v-model="checked" >
    <div class="cart" v-for="item in list" :key="item.id">
      <!-- 复选框绑定是购物车ID -->
      <van-checkbox :name="item.id"></van-checkbox>
      <van-swipe-cell>
        <van-card 
          :price="item.total" 
          :desc="'库存：' + item.product.stock" 
          :title="item.product.name" 
          :thumb="item.product.thumb_text"
          @click-thumb="toProductInfo(item.proid)">
          <template #tags>
            <div style="color: #969799">单价: {{ item.price }}</div>
          </template>
          <template #num>
            <van-stepper v-model="item.nums" theme="round" @change="changeNums(item)" />
          </template>
        </van-card>
        <template #right>
          <van-button 
          square 
          text="删除" 
          type="danger" 
          class="delete-button" 
          @click="DelCart(item)" />
        </template>
      </van-swipe-cell>
    </div>
  </van-checkbox-group>

  <!-- 提交动作栏 -->
  <van-submit-bar :price="total" button-text="确认订单" @submit="onSubmit">
    <van-checkbox v-model="checkedAll" @click="changeAll">全选</van-checkbox>
  </van-submit-bar>

  <!-- 底部 -->
  <tabbar />
</template>
<script setup>
    import tabbar from "@/components/tabbar.vue";
    import { computed } from "vue";

    const { proxy } = getCurrentInstance();
    const back = () => proxy.$router.go(-1);
    const checked = ref([]);
    const checkedAll = ref(false);
    const list = ref([]);

    let proid = proxy.$route.query.hasOwnProperty("proid") ? proxy.$route.query.proid : 0;
    proid = ref(proid);

    let business = proxy.$cookies.get("business") ? proxy.$cookies.get("business") : {};
    onBeforeMount(() => {
      getCartData();
    });

    //获取购物车信息
    const getCartData = async () => {
      let result = await proxy.$POST({
        url: "/cart/index",
        params: {
          busid: business.id,
        },
      });
      if (result.code == 1) {
        list.value = result.data;
      }
    };

    //获取总金额
    const total = computed(() => {
      let nums = 0
      list.value.forEach((item) => {
        if (checked.value.includes(item.id)) {
          nums += parseFloat(item.total)
        }
      })

      //购物车单选 --> 所有商品被选中 全选按钮为选中状态
      if(checked.value.length > 0 && checked.value.length >= list.value.length)
      {
        checkedAll.value = true;
      }else
      {
        checkedAll.value = false
      }

      return nums * 100;
    });

    //点击购物车中商品图片跳转详情页面
    const toProductInfo = (proid) => {
      proxy.$router.push({
        path: '/product/info',
        query: {proid: proid}
      });
    }

    //全选按钮
    const changeAll = () => {
      if(checkedAll.value == true)
      {
        checked.value = list.value.map((item => item.id));
      }else
      {
        checked.value = [];
      }
    }

    //实时更新加入购物车的商品数量
    const changeNums = async (val) =>{
      let result = await proxy.$POST({
        url: "/cart/edit",
        params: {
          cartid: val.id,
          nums: val.nums,
        },
      });
      getCartData();
      if(result.code == 0)
      {
        proxy.$fail(result.msg);
        return false;
      }
    }

    //移出购物车
    const DelCart = (val) => {
      proxy
        .$confirm({
          message: "是否确认删除" + val.product.name + "?",
        })
        //确认删除 --> 采取异步请求对数据进行删除
        .then(async () =>{
          let result = await proxy.$POST({
            url: "/cart/del",
            params: {
              cartid: val.id,
            },
          });
          
          if(result.code == 0)
          {
            proxy.$fail(result.msg);
            return false;
          }else
          {
            proxy.$success(result.msg);
            getCartData();
          }
        })
        .catch(() => {});
    }

    

    //提交事件 --> 产生订单
    const onSubmit = () => {
      if(checked.value.length <= 0)
      {
        proxy.$fail("请选择下单的商品");
        return false;
      }
      proxy.$router.push({
        path: "/product/confirm",
        query: { cartids: checked.value.toString() },
      });
    }
    

</script>
<style scoped>
  :deep(.cart) {
    display: flex;
    width: 100%;
  }

  ::v-deep .van-swipe-cell {
    width: 100%;
  }

  .delete-button {
    height: 100%;
  }

  :global(.van-submit-bar) {
    bottom: 60px;
  }
</style>
